<?php
/**
 * Created by PhpStorm.
 * Script Name: Media.php
 * Create: 2022/04/15
 * Description: 素材管理
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace app\admin\controller;

use app\common\model\MediaImage;
use app\common\model\MediaFile;
use app\common\model\MediaText;
use app\common\model\MediaVideo;
use app\common\model\MediaLink;
use app\common\model\Upload;
use think\Db;
use think\facade\Log;

class Media extends Bbase
{
    /**
     * @var Upload
     */
    private $uploadM;
    /**
     * @var MediaLink
     */
    private $linkM;
    /**
     * @var MediaImage
     */
    private $imageM;
    /**
     * @var MediaText
     */
    private $textM;
    /**
     * @var MediaFile
     */
    private $fileM;
    /**
     * @var MediaVideo
     */
    private $videoM;

    private $types = [
        'text','image', 'video', 'file', 'link'
    ];
    private $adminId;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->uploadM = new Upload();
        $this->imageM = new MediaImage();
        $this->textM = new MediaText();
        $this->fileM = new MediaFile();
        $this->videoM = new MediaVideo();
        $this->linkM = new MediaLink();
        $this->adminId = $this->adminInfo['id'];
        $this->assign('config', config('system.upload'));
        set_time_limit(0);
    }

    /**
     * 素材上传
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function uploadPost(){
        if(request()->isPost()) {
            $post_data = input('');
            $res = $this->uploadM->upload($_FILES, Upload::config($post_data['type']), ['uid' => $this->adminInfo['id']]);

            if($res['code']){
                foreach ($res['data'] as $item){
                    $insert_data = [
                        'admin_id' => $item['uid'],
                        'title' => $item['original_name'],
                        'url' => $item['url'],
                        'size' => $item['size'],
                        'ext' => $item['ext'],
                        'location' => $item['location']
                    ];
                    $data = model('media_' . $post_data['type'])->addOne($insert_data);
                }
                $this->success('上传成功');
            }else{
                $this->error($res['msg']);
            }
        }
    }

    /**
     * 删除素材
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function delPost(){
        $post_data = input();
        $ids = $post_data['ids'];
        $model = model('media_'.$post_data['type']);
        Db::startTrans();
        try {
            foreach ($ids as $id){
                $data = $model->getOne(['admin_id' => $this->adminInfo['id'], 'id' => $id]);
                if($model->delOne(['admin_id' => $this->adminInfo['id'], 'id' => $id])){
                    !empty($data['location']) && strtolower($data['location']) == 'local' && @unlink($data['path']); //删除本地文件
                }
                //refresh
                $model->getOneByMap(['id' => $data['id'], 'admin_id' => $this->adminId], true, 1);
            }
            $res = true;
            Db::commit();
        }catch (\Exception $e){
            Log::error($e->getMessage());
            Db::rollback();
            $res = false;
        }
        if($res === false){
            $this->error('系统错误，请刷新重试');
        }
        $this->success('删除成功');
    }

    /**
     * 素材列表
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function index(){
        $types = [
            'text' => '文本',
            'image' => '图片',
            'file' => '文件',
            'video' => '视频',
            'link' => '分享链接',
        ];

        $type = input('type', 'image');
        $search_key = input('search_key', '');
        $where = ['admin_id' => $this->adminInfo['id']];

        $search_key && $where['title'] = ['like', '%'.$search_key.'%'];
        $type == 'news' && $where['pid'] = 0;
        $data_list = model('media_' . $type)->page(12, $where, ['id' => 'desc'], true, 1);
        $pager = $data_list->appends(['type' => $type, 'search_key' => $search_key])->render();

        $assign = [
            'data_list' => $data_list,
            'type' => $type,
            'types' => $types,
            'pager' => $pager
        ];
        return $this->show($assign);
    }

    /**
     * frame素材列表
     * @return mixed
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function handle(){
        $params = input();
        if(empty($params['type'])){
            $type = 'image';
        }else{
            if(in_array($params['type'], $this->types)){
                $type = $params['type'];
            }else{
                echo "type参数错误";exit;
            }
        }
        if(method_exists($this, $type)){
            return call_user_func([$this, $type]);
        }else{
            echo $type . "方法不存在";exit;
        }
    }

    /**
     * 应用插件
     * @return mixed
     * @throws \think\exception\DbException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function addon(){
        $field = input('field', ''); //目标input框
        $where = ['mpid' => $this->mpId, 'a.status' => 1];
        $data_list = $this->mpAddonM->pageJoin([
            'alias' => 'ma',
            'join' => [['addons a', 'a.addon=ma.addon']],
            'page_size' => 7,
            'where' => $where,
            'field' => ['a.id','a.name', 'a.desc', 'a.logo'],
            'order' => ['ma.id' => 'desc'],
            'refresh' => 1
        ]);
        $pager = $data_list->render();
        $assign = ['data_list' => $data_list, 'pager' => $pager, 'field' => $field];
        return $this->show($assign, __FUNCTION__);
    }

    /**
     * 链接
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function link(){
        $field = input('field', ''); //目标input框
        $where = ['admin_id' => $this->adminId];
        $data_list = $this->linkM->page(10, $where, ['id' => 'desc'], 'id,title,desc,image_url,url', 1);
        $pager = $data_list->render();
        $assign = ['data_list' => $data_list, 'pager' => $pager, 'field' => $field];
        return $this->show($assign, __FUNCTION__);
    }

    /**
     * 视频
     * @return mixed
     * @throws \think\exception\DbException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function video(){
        $field = input('field', ''); //目标input框
        $where = ['admin_id' => $this->adminId];

        $data_list = $this->videoM->page(12, $where, ['id' => 'desc'], 'id,url,title', 1);
        $pager = $data_list->render();
        $assign = ['data_list' => $data_list, 'pager' => $pager, 'field' => $field];
        return $this->show($assign, __FUNCTION__);
    }

    /**
     * 文件
     * @return mixed
     * @throws \think\exception\DbException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function file(){
        $field = input('field', ''); //目标input框
        $where = ['admin_id' => $this->adminId];

        $data_list = $this->fileM->page(10, $where, ['id' => 'desc'], 'id,title,url', 1);
        $pager = $data_list->render();
        $assign = ['data_list' => $data_list, 'pager' => $pager, 'field' => $field];
        return $this->show($assign, __FUNCTION__);
    }

    /**
     * 文本
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function text(){
        if(request()->isPost()){
            $post_data = input('post.');
            $post_data['admin_id'] = $this->adminId;
            if($res = $this->textM->addOne($post_data)){
                $this->success('保存成功');
            }
            $this->error('保存失败，请刷新重试');
        }
        $field = input('field', ''); //目标input框
        $where = ['admin_id' => $this->adminId];
        $data_list = $this->textM->page(10, $where, ['id' => 'desc'], 'id,content', 1);
        $pager = $data_list->render();
        $assign = ['data_list' => $data_list, 'pager' => $pager, 'field' => $field];
        return $this->show($assign, __FUNCTION__);
    }

    /**
     * 图片
     * @return mixed
     * @throws \think\exception\DbException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function image(){
        $field = input('field', ''); //目标input框
        $where = ['admin_id' => $this->adminId];
        $data_list = $this->imageM->page(12, $where, ['id' => 'desc'], 'id,url,title', 1);
        $pager = $data_list->render();
        $assign = ['data_list' => $data_list, 'pager' => $pager, 'field' => $field];
        return $this->show($assign, __FUNCTION__);
    }
}